﻿namespace TradePublish.SysThread.Grasp
{
    using log4net;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Reflection;
    using System.Text;
    using System.Threading;
    using SysThread.Grasp;
    using TradePublish.Entity;
    using TradePublish.Service;

    public class ClientTaskThread
    {
        private Thread doThread;
        private ILog log = null;
        private List<ClientTaskSubThread> subThreads = new List<ClientTaskSubThread>();
        private TradePublishManager tradePublishManager = new TradePublishManager();
        private int threadCount = 10;//子线程数量
        public ClientTaskThread()
        {
            this.log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        public void start()
        {
            for (int i = 0; i < threadCount; i++)
            {
                ClientTaskSubThread item = new ClientTaskSubThread {
                    id = i,
                    isRunning = false
                };
                item.start();
                this.subThreads.Add(item);
            }
            this.log.Info("已开启"+threadCount+"个子线程.");
            this.doThread = new Thread(new ThreadStart(this.threadWork));
            this.doThread.IsBackground = true;
            this.doThread.Start();
        }

        private void threadWork()
        {
            int readySubThreadCount = threadCount;//当前有几个子线程等待任务？

            #region 先获得上次软件关闭前未完任务,并分配，直到全部完成。
            DataSet ds = null;
            while (true)
            {
                ds = tradePublishManager.findUnFinishedTask(readySubThreadCount * 10);//内部异常自己处理
                if (ds == null || ds.Tables == null || ds.Tables[0].Rows == null || ds.Tables[0].Rows.Count == 0)
                {
                    break;
                }
                //下发任务到子线程中。
                List<TradePublishVo> l = new List<TradePublishVo>();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    TradePublishVo vo = new TradePublishVo();
                    #region copy属性
                    vo.id = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"]);
                    vo.issue = Convert.ToInt32(ds.Tables[0].Rows[i]["ISSUE"]);
                    vo.regNo = ds.Tables[0].Rows[i]["REG_NO"].ToString();
                    vo.category = Convert.ToInt32(ds.Tables[0].Rows[i]["CATEGORY"]);
                    //可能为空
                    vo.classNo = Convert.ToInt32((ds.Tables[0].Rows[i]["CLASS_NO"] == null || ds.Tables[0].Rows[i]["CLASS_NO"].ToString().Equals("")) ? "0" : ds.Tables[0].Rows[i]["CLASS_NO"]);
                    vo.tradeName = ds.Tables[0].Rows[i]["TRADE_NAME"].ToString();
                    vo.applyUserName = ds.Tables[0].Rows[i]["APPLY_USER_NAME"].ToString();
                    vo.applyUserAddress = ds.Tables[0].Rows[i]["APPLY_USER_ADDRESS"].ToString();
                    vo.proxyUserName = ds.Tables[0].Rows[i]["PROXY_USER_NAME"].ToString();
                    //
                    vo.hasGrasped = Convert.ToInt32(ds.Tables[0].Rows[i]["HAS_GRASPED"]) == 1 ? true : false;
                    vo.hasAntiSearch = Convert.ToInt32(ds.Tables[0].Rows[i]["HAS_ANTI_SEARCH"]) == 1 ? true : false;
                    vo.hasStatusSearch = Convert.ToInt32(ds.Tables[0].Rows[i]["HAS_STATUS_SEARCH"]) == 1 ? true : false;

                    #endregion
                    l.Add(vo);
                    if (l.Count >= 10 || i == ds.Tables[0].Rows.Count - 1)
                    {
                        //给子线程任务
                        for (int x = 0; x < subThreads.Count; x++)
                        {
                            if (!subThreads[x].isRunning)
                            {
                                subThreads[x].tradePublishs = l;
                                subThreads[x].isRunning = true;
                                log.Info("上次未完任务分配给ClientTaskSubThread-" + subThreads[x].id + ".");
                                l = new List<TradePublishVo>();
                                break;
                            }
                        }
                    }
                }
                #region 一直等待所有子线程全部完成
                while (true)
                {
                    readySubThreadCount = 0;
                    for (int x = 0; x < subThreads.Count; x++)
                    {
                        if (!subThreads[x].isRunning)
                        {
                            //该进程已停止了。
                            readySubThreadCount++;
                        }
                    }
                    if (readySubThreadCount < threadCount)
                    {
                        Thread.Sleep(15000);//休息15秒
                    }
                    else
                    {
                        break;
                    }
                }
                #endregion
            }
            #endregion

            while (true)
            {
                #region 看看有多少个子线程等待分配任务
                while (true)
                { 
                    readySubThreadCount = 0;
                    for (int x = 0; x < subThreads.Count; x++)
                    {
                        if (!subThreads[x].isRunning)
                        {
                            //该进程已停止了。
                            readySubThreadCount++;
                        } 
                    }
                    if (readySubThreadCount == 0)
                    {
                        Thread.Sleep(15000);//休息15秒
                    }
                    else
                    {
                        break;
                    }
                }
                #endregion

                //获得本客户端的任务。
                ds = tradePublishManager.findClientTask(readySubThreadCount * 10 );//内部异常自己处理
                if (ds == null || ds.Tables == null || ds.Tables.Count == 0 || ds.Tables[0].Rows == null || ds.Tables[0].Rows.Count == 0)
                {
                    //没有需要处理的
                    Thread.Sleep(120000);//休息2分钟
                    continue;
                }
                else
                {
                    //下发任务到子线程中。
                    List<TradePublishVo> l = new List<TradePublishVo>();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        TradePublishVo vo = new TradePublishVo();
                        #region copy属性
                        vo.id = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"]);
                        vo.issue = Convert.ToInt32(ds.Tables[0].Rows[i]["ISSUE"]);
                        vo.regNo = ds.Tables[0].Rows[i]["REG_NO"].ToString();
                        vo.category = Convert.ToInt32(ds.Tables[0].Rows[i]["CATEGORY"]);
                        //可能为空
                        vo.classNo = Convert.ToInt32((ds.Tables[0].Rows[i]["CLASS_NO"] == null || ds.Tables[0].Rows[i]["CLASS_NO"].ToString().Equals("")) ? "0" : ds.Tables[0].Rows[i]["CLASS_NO"]);
                        vo.tradeName = ds.Tables[0].Rows[i]["TRADE_NAME"].ToString();
                        vo.applyUserName = ds.Tables[0].Rows[i]["APPLY_USER_NAME"].ToString();
                        vo.applyUserAddress = ds.Tables[0].Rows[i]["APPLY_USER_ADDRESS"].ToString();
                        vo.proxyUserName = ds.Tables[0].Rows[i]["PROXY_USER_NAME"].ToString();
                        //
                        vo.hasGrasped = Convert.ToInt32(ds.Tables[0].Rows[i]["HAS_GRASPED"]) == 1 ? true : false;
                        vo.hasAntiSearch = Convert.ToInt32(ds.Tables[0].Rows[i]["HAS_ANTI_SEARCH"]) == 1 ? true : false;
                        vo.hasStatusSearch = Convert.ToInt32(ds.Tables[0].Rows[i]["HAS_STATUS_SEARCH"]) == 1 ? true : false;


                        #endregion
                        l.Add(vo);
                        if (l.Count >= 10 || i == ds.Tables[0].Rows.Count - 1)
                        {
                            //给子线程任务
                            for (int x = 0; x < subThreads.Count; x++)
                            {
                                if (!subThreads[x].isRunning)
                                {
                                    subThreads[x].tradePublishs = l;
                                    subThreads[x].isRunning = true;
                                    log.Info("子任务分配给ClientTaskSubThread-" + subThreads[x].id + ".");
                                    l = new List<TradePublishVo>();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

